package com.taoym.voucher.common.response;

import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.AllArgsConstructor;
import lombok.Data;

import java.io.Serializable;
import java.time.LocalDateTime;

/**
 * @author: taoym
 * @date: 2021/4/12 22:57
 * @desc: todo
 */
@Data
@AllArgsConstructor
public class Response<T> implements Serializable {
    /**
     * 状态码
     */
    private String code;
    /**
     * 状态信息
     */
    private String msg;
    /**
     * 返回值
     */
    private T data;
    /**
     * 当前时间戳
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private LocalDateTime timestamp;

    public static <T> Response<T> success(T data) {
        return createResponse(ResponseStatusCode.SUCCESS.getCode(), ResponseStatusCode.SUCCESS.getMsg(), data);
    }

    public static <T> Response<T> fail(ResponseStatusCode responseStatusCode) {
        return createResponse(responseStatusCode.getCode(), responseStatusCode.getMsg(), null);
    }

    public static <T> Response<T> fail(String code, String msg) {
        return createResponse(code, msg, null);
    }

    public static <T> Response<T> fail(String code, String msg, T data) {
        return createResponse(code, msg, data);
    }

    private static <T> Response<T> createResponse(String code, String msg, T data) {
        return new Response<>(code, msg, data, LocalDateTime.now());
    }
}
